<template>
  <div class="login">
    <el-row>
      <!-- offset:偏移量,向右移动的格数 -->
      <!-- span:自己占有的格数 -->
      <el-col :offset="8" :span="8">
        <div class="grid-content bg-purple">
          <!-- model:表单的数据 -->
          <!-- rules:表单的校验规则 -->
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <!-- prop: 检验时对应的字段 -->
            <el-form-item label="用户名" prop="username">
              <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="ruleForm.password" show-password></el-input>
            </el-form-item>

            <el-form-item>
              <el-button class="login-btn" type="primary" @click="submitForm"
                >立即登录</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 表单的数据,向后台传值时就用这个
      ruleForm: {
        username: "123456",
        password: "123456",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    submitForm() {
      // this.$refs.ruleForm  找到子组件,调用validate方法,用来校验表单
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 为真表示校验通过
          // console.log(this.ruleForm);
          this.$http
            .post("/userlogin", this.ruleForm)
            .then((res) => {
              if (res.code === 200) {
                // 登录成功,保存用户数据，跳转到首页
                this.$store.commit('saveUserInfo', res.list)
                this.$router.push('/')
              } else {
                // 失败
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          // 为假表示校验不通过
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
<style>
.grid-content {
  height: 400px;
}
/* 覆盖elementui样式 */
.login .login-btn {
  width: 100%;
}
</style>